package douyin

import (
	"context"
	"encoding/json"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpc"
	"io"
)

type JsCodeReq struct {
	Appid         string `json:"appid"`
	Secret        string `json:"secret"`
	Code          string `json:"code"`
	AnonymousCode string `json:"anonymous_code"`
}

type JsCodeResp struct {
	ErrNo   int    `json:"err_no"`
	ErrTips string `json:"err_tips"`
	Data    struct {
		SessionKey      string `json:"session_key"`
		Openid          string `json:"openid"`
		AnonymousOpenid string `json:"anonymous_openid"`
		Unionid         string `json:"unionid"`
	} `json:"data"`
}

func (c *DouYinClient) JsCode2Session(req *JsCodeReq) (*JsCodeResp, error) {
	req.Appid = c.conf.AppId
	req.Secret = c.conf.Secret

	do, err := httpc.Do(context.Background(), "POST", Code2SessionURL, req)

	//resp, err := tools.Post(Code2SessionURL, req)
	if err != nil {
		logx.Errorf("err:%+v", err)
		return nil, err
	}

	var data JsCodeResp
	//marshal, err := json.Marshal(do.Header)
	//logx.Info(string(marshal))
	//io.Copy(os.Stdout,)
	//err = httpc.ParseJsonBody(do, &data)
	all, err := io.ReadAll(do.Body)
	err = json.Unmarshal(all, &data)

	if err != nil {
		logx.Errorf("err:%+v", err)
		return nil, err
	}
	return &data, nil
}
